package cn.yuemouren.queue;

import com.sun.glass.ui.Size;

/**
 * @Author: Timi
 * @Description: 链表实现队列 (头出尾入)
 * @Date: 2020/5/14 15:58
 */
public class LinkedListQueue<T> implements Queue<T>{

    /**
     * 链表中节点类
     */
    private class Node{
        private T t;
        private Node next;

        public Node(){
            this(null);
        }

        public Node(T t){
            this(t,null);
        }

        public Node(T t,Node next){
            this.t = t;
            this.next = next;
        }
    }

    private Node head;
    private Node tail;
    private int size;

    public LinkedListQueue(Node head, Node tail, int size) {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    @Override
    public void enQueue(T t) {
        if(tail == head){
            tail = new Node();
            head = tail;
        } else{
            tail.next = new Node(t);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public T dnQueue() {
        if(isEmpty()){
            throw new IllegalArgumentException("queue is empty");
        }
        Node dnNode = head;
        head = head.next;
        dnNode.next = null;
        if(tail == null){
            head = null;
        }
        size--;
        return dnNode.t;
    }

    @Override
    public T getHead() {
        if(isEmpty()){
            throw new IllegalArgumentException("queue is empty");
        }
        return head.t;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("LinkedListQueue: [");
        Node cur = head;
        if(null != cur){
            sb.append(cur.t+",");
            cur = cur.next;
        }
        sb.append("] tail");
        return sb.toString();
    }
}
